import Vue from 'vue'
import {getLocal, setLocal} from "../utils/local";
import {MyMap} from "../utils/lodash";

function withStore(component) {
    return {
        mounted() {
            this.initStore()
        },
        methods: {
            initStore() {
                var self = this;
                var keys = Object.keys(self.$store.state)
                for (var i = 0; i < keys.length; i++) {
                    var key1 = keys[i]
                    var keys2 = Object.keys(self.$store.state[key1])
                    for (var j = 0; j < keys2.length; j++) {
                        var key3 = keys2[i]
                        var value = localStorage.getItem(key3)

                        if (Array.isArray(value) && value.length != 0) {
                            self.setStore(`${key1}.${key3}`, value)
                            return false
                        } else {
                            if (value) {
                                self.setStore(`${key1}.${key3}`, value)
                            }
                        }
                    }
                }
            },
            setStore(namespace_key, value) {
                var namespance = namespace_key.split(".")[0]
                var key = namespace_key.split(".")[1]
                setLocal(namespace_key, value)
                this.$store.commit(`${namespance}/snapShot`, {[key]: value})
            },
            getStore(namespace_key, fromLocal = false) {
                if (fromLocal) return getLocal(namespace_key)
                var namespance = namespace_key.split(".")[0]
                var key = namespace_key.split(".")[1]
                var vuex_store_result = this.$store.state[namespance][key]
                if (Array.isArray(vuex_store_result)) {
                    if (vuex_store_result.length == 0) return getLocal(namespace_key) || getLocal(namespace_key)
                }
                return vuex_store_result || getLocal(namespace_key)
            },
        },
        extends: component,
    }
}

export default withStore

